﻿using System;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using EIP.AgreementRegistryServices;

namespace XRM.Security.Api.EipInteraction
{
    public class EipService : IEipService
    {
        public bool Authorize( X509Certificate certificate, String participantName, String serviceName, String serviceVersion, String methodName )
        {
            var tokenRequest = new AuthorizationTokenRequestType
            {
                Certificate = certificate.GetRawCertData(),
                DateTime = DateTime.Now,
                ParticipantName = participantName,
                ServiceName = serviceName,
                ServiceVersionName = serviceVersion,
                MethodName = methodName
            };

            using ( var channelFactory = new ChannelFactory<IIdentificationService>( "WebHttpBinding_IAgreementService" ) )
            {
                var service = channelFactory.CreateChannel();
                var authToken = service.Authorize( tokenRequest );
                return authToken.ResultCode == AuthorizationResultCodeType.Success &&
                    (authToken.ParticipantInfo.Name == participantName || authToken.Role.Any( s => s.Level == RoleLevelType.Service ));
            }
        }
    }
}
